//
//  SearchViewController.m
//  bondwatch_purecode
//
//  Created by Jason Yuan on 6/9/15.
//  Copyright (c) 2015 Sumridge. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchTableViewCell.h"
#import "AddToWatchListView.h"

#define SEARCHBARCOLOR [UIColor colorWithRed:244.0/255.0 green:170.0/255.0 blue:43.0/255.0 alpha:1.0]
#define SEARCHBARFONT [UIFont fontWithName:@"Arial-BoldMT" size:16.0]

@interface SearchViewController () <UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate, SearchTableViewCellDelegate>
{
    UISearchBar *mySearchBar;
    UITableView *resultTableView;
    NSArray *searchArray;
    NSString *type;
}

@end

@implementation SearchViewController

@synthesize delegate;

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"Search";
    [self.view setBackgroundColor:[UIColor whiteColor]];
    type = @"Ticker";
    
    mySearchBar = [[UISearchBar alloc] init];
    mySearchBar.delegate = self;
    mySearchBar.showsScopeBar = YES;
    mySearchBar.placeholder = @"Search";
    [[self searchSubviewsForTextFieldIn:mySearchBar] setBackgroundColor:SEARCHBARCOLOR];
    [[self searchSubviewsForTextFieldIn:mySearchBar] setFont:SEARCHBARFONT];
    mySearchBar.tintColor = SUMRIDGECOLOR;
    mySearchBar.scopeButtonTitles = @[@"Ticker", @"Cusip", @"Back"];
    [self.view addSubview: mySearchBar];
    
    [mySearchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(20);
    }];
    
    resultTableView = [[UITableView alloc] init];
    resultTableView.separatorInset = UIEdgeInsetsZero;
    resultTableView.layoutMargins = UIEdgeInsetsZero;
    resultTableView.dataSource = self;
    resultTableView.delegate = self;
    
    [self.view addSubview:resultTableView];
    
    [resultTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(108);
        make.bottom.equalTo(self.view);
    }];
}

- (void)loadData:(NSDictionary *)params
{
    
}

- (void)getSearchData {
    NSDictionary *params;
    if ([type isEqualToString:@"Ticker"]) {
        params = @{@"cusips":@"",
                   @"minQuantrity":@"",
                   @"maxQuantrity":@"",
                   @"minMaturity":@"",
                   @"maxMaturity":@"",
                   @"minSPRating":@"",
                   @"maxSPRating":@"",
                   @"minCoupon":@"",
                   @"maxCoupon":@"",
                   @"minPrice":@"",
                   @"maxPrice":@"",
                   @"minYtm":@"",
                   @"maxYtm":@"",
                   @"minYtw":@"",
                   @"maxYtw":@"",
                   @"minCurrentYield":@"",
                   @"maxCurrentYield":@"",
                   @"side":@"1",
                   @"ticker":mySearchBar.text,
                   @"sector":@[],
                   @"couponType":@[],
                   @"capStructure":@[],
                   @"doCount":@"true",
                   @"dealerFlag":@"Y",
                   @"dealer":@[@"0",@"2",@"8",@"15"],
                   @"marketSectorDes":@[@"COR"],
                   @"limit":@"100",
                   @"page":@"1"};
    } else {
        params = @{@"cusips":mySearchBar.text,
                   @"minQuantrity":@"",
                   @"maxQuantrity":@"",
                   @"minMaturity":@"",
                   @"maxMaturity":@"",
                   @"minSPRating":@"",
                   @"maxSPRating":@"",
                   @"minCoupon":@"",
                   @"maxCoupon":@"",
                   @"minPrice":@"",
                   @"maxPrice":@"",
                   @"minYtm":@"",
                   @"maxYtm":@"",
                   @"minYtw":@"",
                   @"maxYtw":@"",
                   @"minCurrentYield":@"",
                   @"maxCurrentYield":@"",
                   @"side":@"1",
                   @"ticker":@"",
                   @"sector":@[],
                   @"couponType":@[],
                   @"capStructure":@[],
                   @"doCount":@"true",
                   @"dealerFlag":@"Y",
                   @"dealer":@[@"0",@"2",@"8",@"15"],
                   @"marketSectorDes":@[@"COR"],
                   @"limit":@"100",
                   @"page":@"1"};
    }
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
    [requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = requestSerializer;
    [manager POST:SEARCHURL parameters:params success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        searchArray = [responseObject objectForKey:@"data"];
        DDLogVerbose(@"Search Array is:\n%@", searchArray);
        [resultTableView reloadData];
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        DDLogError(@"Search Error:\n%@", error);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark- Searchbar delegate

- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if (range.length == 0 && [text isEqualToString:@" "]) {
        [searchBar endEditing:NO];
        
        // Getting the Detail Data
        [self getSearchData];
    }
    return YES;
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}

- (void)searchBarResultsListButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
    
    if (![searchBar.text isEqualToString:@""]) {
        [searchBar endEditing:NO];
        // Getting the Detail Data
        NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:type, @"type", searchBar.text, @"search", nil];
        [self loadData:params];
    }
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
    
    if (![searchBar.text isEqualToString:@""]) {
        [searchBar endEditing:NO];
        // Getting the Detail Data
        NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:type, @"type", searchBar.text, @"search", nil];
        [self loadData:params];
    }
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    return YES;
}

- (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope {
    switch (selectedScope) {
        case 0:
        {
            type = @"Ticker";
            break;
        }
        case 1:
        {
            type = @"Cusip";
            break;
        }
        case 2:
        {
            [self.navigationController popViewControllerAnimated:YES];
            break;
        }
        default:
            break;
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    if (searchArray != nil) {
        tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        tableView.separatorColor = SUMRIDGECOLOR;
        return [searchArray count];
    } else {
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 32;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Configure the cell...
    SearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SearchTableViewCell"];
    
    if (cell == nil) {
        cell = [[SearchTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"SearchTableViewCell"];
        cell.delegate = self;
        [cell setUIFrame];
        cell.separatorInset = UIEdgeInsetsZero;
        cell.layoutMargins = UIEdgeInsetsZero;
    }
    
    NSDictionary *dict = [searchArray objectAtIndex:indexPath.row];
    [cell setLabelText:dict];
    return cell;
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *data = [searchArray objectAtIndex:indexPath.row];
    [self.delegate selectWatchBond:data];
    [self.navigationController popViewControllerAnimated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 30)];
    
    UIColor *titleColor = [UIColor colorWithRed:0.0 green:0.0 blue:247.0/255.0 alpha:1.0];
    
    UILabel *issuerTitle = [[UILabel alloc] init];
    issuerTitle.textAlignment = NSTextAlignmentLeft;
    issuerTitle.textColor = titleColor;
    issuerTitle.font = ARIALBOLD10;
    issuerTitle.text = @"Issuer";
    
    UILabel *tickerTitle = [[UILabel alloc] init];
    tickerTitle.textAlignment = NSTextAlignmentLeft;
    tickerTitle.textColor = titleColor;
    tickerTitle.font = ARIALBOLD10;
    tickerTitle.text = @"Ticker";
    
    UILabel *couponTitle = [[UILabel alloc] init];
    couponTitle.textAlignment = NSTextAlignmentRight;
    couponTitle.textColor = titleColor;
    couponTitle.font = ARIALBOLD10;
    couponTitle.text = @"Coupon";
    
    UILabel *maturityTitle = [[UILabel alloc] init];
    maturityTitle.textAlignment = NSTextAlignmentCenter;
    maturityTitle.textColor = titleColor;
    maturityTitle.font = ARIALBOLD10;
    maturityTitle.text = @"Maturity";
    
    UILabel *ratingTitle = [[UILabel alloc] init];
    ratingTitle.textAlignment = NSTextAlignmentLeft;
    ratingTitle.textColor = titleColor;
    ratingTitle.font = ARIALBOLD10;
    ratingTitle.text = @"Rating";
    
    UILabel *issAmtTitle = [[UILabel alloc] init];
    issAmtTitle.textAlignment = NSTextAlignmentRight;
    issAmtTitle.textColor = titleColor;
    issAmtTitle.font = ARIALBOLD10;
    issAmtTitle.text = @"IssAmt(mm)";
    
    [headerView addSubview:issuerTitle];
    [headerView addSubview:tickerTitle];
    [headerView addSubview:couponTitle];
    [headerView addSubview:maturityTitle];
    [headerView addSubview:ratingTitle];
    [headerView addSubview:issAmtTitle];
    
    [issuerTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(headerView).offset(5);
        make.top.equalTo(headerView);
        make.bottom.equalTo(headerView);
        make.width.mas_equalTo(60);
    }];
   
    [tickerTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(issuerTitle.mas_right);
        make.top.equalTo(headerView);
        make.bottom.equalTo(headerView);
        make.width.mas_equalTo(35);
    }];
    
    [couponTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(tickerTitle.mas_right);
        make.top.equalTo(headerView);
        make.bottom.equalTo(headerView);
        make.width.mas_equalTo(40);
    }];
    
    [maturityTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(couponTitle.mas_right);
        make.top.equalTo(headerView);
        make.bottom.equalTo(headerView);
        make.width.mas_equalTo(70);
    }];
    
    [ratingTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(maturityTitle.mas_right);
        make.top.equalTo(headerView);
        make.bottom.equalTo(headerView);
        make.width.mas_equalTo(60);
    }];
    
    [issAmtTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(ratingTitle.mas_right);
        make.top.equalTo(headerView);
        make.bottom.equalTo(headerView);
        make.width.mas_equalTo(60);
    }];
    
    return headerView;
}

- (UITextField*)searchSubviewsForTextFieldIn:(UIView*)view
{
    if ([view isKindOfClass:[UITextField class]]) {
        return (UITextField*)view;
    }
    UITextField *searchedTextField;
    for (UIView *subview in view.subviews) {
        searchedTextField = [self searchSubviewsForTextFieldIn:subview];
        if (searchedTextField) {
            break;
        }
    }
    return searchedTextField;
}

#pragma Search Table view cell delegate

- (void)addToWatchList:(NSDictionary *)data {
//    [BWNetwork addToWatchList:data];
    AddToWatchListView *addToWatchListView = [[AddToWatchListView alloc] initWithFrame:self.view.bounds];
    addToWatchListView.myData = data;
    [addToWatchListView setBackgroundColor:[UIColor colorWithRed:1 green:1 blue:1 alpha:0.8]];
    [self.view addSubview:addToWatchListView];
}

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

@end
